﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;

public class ClientManager : BaseManager
{

	private string _ip = "192.168.1.4";
	private int _port = 7788;
	private TcpClient _tcpClient;
	private int _len;
	private Boolean _isConnected;
	private Boolean _isHead;
	
	
	public override void OnInit()
	{
		try
		{
			_tcpClient = new TcpClient();
			_tcpClient.Connect(_ip,_port);
			_isConnected = true;
			_isHead = true;
		}
		catch (Exception e)
		{
			Debug.Log("连接服务器失败");
			MsgPanel msgPanel = (MsgPanel) UnityFacade.Instance.UiManager.PushPanel(PanelType.Msg);
			msgPanel.SyncShow("fail","连接服务器失败");
			
		}
	}

	public override void OnUpdate()
	{
		if (_isConnected)
		{
			ReceiveMsgFromServer();
		}
	}

	/// <summary>
	/// 将请求对象（已转化为bytes）发送给服务端
	/// </summary>
	/// <param name="dateBytes"></param>
	public void SendMsgToServer(byte[] dateBytes)
	{
		byte[] fullDataBytes = new byte[4+dateBytes.Length];
		ConverterTool.IntToBytes(dateBytes.Length).CopyTo(fullDataBytes,0);
		dateBytes.CopyTo(fullDataBytes,4);
		_tcpClient.GetStream().Write(fullDataBytes,0,fullDataBytes.Length);
	}
	
	
	public override void OnDestroy()
	{
		try
		{
			if (_tcpClient != null)
			{
				_tcpClient.Close();
			}
		}
		catch (Exception e)
		{
			
			Debug.Log("断开连接失败");
		}
	}

	/// <summary>
	/// 接收服务端请求
	/// </summary>
	private void ReceiveMsgFromServer()
	{
		NetworkStream stream = _tcpClient.GetStream();
                if (!stream.CanRead)
                {
                    return;
                }
                //读取消息体的长度
                if (_isHead)
                {
                    if (_tcpClient.Available < 4)
                    {
                        return;
                    }
                    byte[] lenByte = new byte[4];
                    stream.Read(lenByte, 0, 4);
                    _len = ConverterTool.BytesToInt(lenByte, 0);
                    _isHead = false;
                }
                //读取消息体内容
                if (!_isHead)
                {
                    if (_tcpClient.Available < _len)
                    {
                        return;
                    }
                    byte[] msgByte = new byte[_len];
                    stream.Read(msgByte, 0, _len);
                    _isHead = true;
                    _len = 0;
                    //生成Response对象，根据这个对象再看具体的执行
                    //解析得到具体消息对象 reponseObj，然后执行具体的操作,利用反射机制
                    NettyResponse responseObj= ConverterTool.DeSerialToResponseObj(msgByte);
                    UnityFacade.Instance.RequestManager.HandleResponse(responseObj);
                }
	}
	
}
